package com.songlanyun.modules.oss.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.*;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.oss.cloud.CloudStorageService;
import com.songlanyun.modules.oss.cloud.OSSFactory;
import com.songlanyun.modules.wechat.config.WxMaConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.util.Map;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.songlanyun.modules.oss.dao.SysOssDao;
import com.songlanyun.modules.oss.entity.SysOssEntity;
import com.songlanyun.modules.oss.service.SysOssService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("sysOssService")
public class SysOssServiceImpl extends ServiceImpl<SysOssDao, SysOssEntity> implements SysOssService {


    @Resource
    private AccountService accountService;

    //微信app id
    @Value("${wx.miniapp.configs[0].appid}")
    private String appid;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Long shopId = MapUtil.getLong(params, "shop_id");
        String resourceType = MapUtil.getStr(params, "resource_type");
        Long date = MapUtil.getLong(params, "date");

        IPage<SysOssEntity> page = this.page(
                new Query<SysOssEntity>().getPage(params),
                new LambdaQueryWrapper<SysOssEntity>()
                        .eq(shopId != null, SysOssEntity::getShopId, shopId)
                        .eq(StringUtils.isNotBlank(resourceType), SysOssEntity::getResourceType, resourceType)
                        .eq(date != null, SysOssEntity::getDate, date)
                        .orderByDesc(SysOssEntity::getCreateTime)
        );

        return new PageUtils(page);
    }

    @Override
    public Long shopUsed(Map<String, Object> params) {
        return baseMapper.shopUsed(params);

    }

    @Override
    @Transactional
    public String saveQRcode(String path, String code) {
        try {
            AccountEntity account = accountService.getByCode(code);
            if (StringUtils.isNotBlank(account.getQrcode())) {
                return account.getQrcode();
            }

            final WxMaService wxService = WxMaConfiguration.getMaService(appid);

            //前端给path
//        path = "pages/index/index";
            path = path + "?code=" + code;//拼接邀请码
            byte[] qrcodeBytes = new byte[0];

            qrcodeBytes = wxService.getQrcodeService().createQrcodeBytes(path, 430);
            String url = getUrl(qrcodeBytes);
            account.setQrcode(url);
            accountService.saveQrcode(account);
            return url;

        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new RRException("上传异常");
        }


    }


    @Override
    public String saveWXcode(String path, String code) {

        try {
            AccountEntity account = accountService.getByCode(code);
            if (StringUtils.isNotBlank(account.getQrcode())) {
                return account.getQrcode();
            }

            final WxMaService wxService = WxMaConfiguration.getMaService(appid);

            //WXSceneSession  分享到聊天界面
            //WXSceneTimeline 分享到朋友圈
            //WXSceneFavorite 分享到微信收藏
            String scene = "WXSceneSession";
//        path = "pages/index/index";
            path = path + "?code=" + code;
            byte[] wxcodeBytes = new byte[0];

            File file = wxService.getQrcodeService().createWxaCodeUnlimit(scene, path);
            wxcodeBytes = Files.readAllBytes(file.toPath());
            String url = getUrl(wxcodeBytes);
            account.setQrcode(url);
            accountService.saveQrcode(account);
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("上传异常");
        }

    }

    private String getUrl(byte[] bytes) {
        String filename = UUIDUtil.getUUID() + System.currentTimeMillis() + ".jpg";

        /********************OSS上传*************************/
        CloudStorageService build = OSSFactory.build();
        String url = build.upload(bytes, "qrcode/" + filename);

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setShopId(0L);
        ossEntity.setDate(DateUtil.getNowTime("yyyy-MM-dd"));
        ossEntity.setSize((long) bytes.length);
        ossEntity.setResourceType("qrcode");

        this.baseMapper.insert(ossEntity);

        return url;
    }
}


